package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 用户端-登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 通过httpClient,构造登录凭证校验请求
        Map map = new HashMap();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");
        String result = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);
        log.info("result:{}", result);

        // 解析结果 获取openid
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.getString("openid");
        if (openid.isEmpty()) {
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }

        // 判断是否为新用户，根据openid查询user表
        User user = userMapper.selectByOpenid(openid);

        // 如果是初始化用户user
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setName(openid.substring(0, 5));
            user.setCreateTime(LocalDateTime.now());
            userMapper.addUser(user);
        }

        // 如果不是直接返回user
        return user;
    }
}
